package com.supermap.qdsearch.utils;

import java.io.Serializable;
import java.util.Arrays;

/**
 * Created by XueQing Wang on 2018/6/14.
 */

public class MyQueue<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private int DEFAULT_SIZE = 10;

    private int size;//保存数组的长度

    private Object[] datas;//定义一个数组用于保存顺序队列的元素

    private int front = 0;//队头

    private int rear = 0;//队尾

    //以默认数组长度创建空顺序队列
    public MyQueue() {
        size = DEFAULT_SIZE;
        datas = new Object[size];
    }


    /**
     * @param t
     * @Title: push
     * @Description: 入队
     */
    public void push(T t) {
        testSize(rear + 1);
        datas[rear++] = t;
    }

    private void testSize(int size) {
        //如果数组的原有长度小于目前所需的长度
        int oldSize = datas.length;
        if (size > oldSize) {
            //默认增大两倍
            int newSize = oldSize * 2;
            if (newSize < size)
                newSize = size;
            // size is usually close to size, so this is a win:
            datas = Arrays.copyOf(datas, newSize);
        }

    }

    /**
     * @return
     * @Title: poll
     * @Description: 出队
     */
    public T poll() {
        if (isEmpty()) {
            throw new IndexOutOfBoundsException("空队列异常");
        }
        //保留队列的front端的元素的值
        T oldValue = (T) datas[front];
        //释放队列的front端的元素
        datas[front++] = null;
        return oldValue;
    }

    /**
     * @return
     * @Title: isEmpty
     * @Description: 判断顺序队列是否为空队列
     */
    public boolean isEmpty() {
        return rear == front;
    }

}
